﻿using System;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Media;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework;
using CoreSharp.Socially.Twitter;
using CoreSharp.Socially;
using CoreSharp.Socially.Facebook;

namespace CoreSharp.ThaiSMS
{
    public partial class MainPage : PhoneApplicationPage
    {
        private SoundEffect _Type = SoundEffect.FromStream(TitleContainer.OpenStream("sounds/type.wav"));
        private SoundEffect _Cant = SoundEffect.FromStream(TitleContainer.OpenStream("sounds/cant.wav"));

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            
            PhoneApplicationService.Current.Deactivated += delegate
            {
                this.SaveState();
            };

            PhoneApplicationService.Current.Activated += delegate
            {
                this.LoadState();
            };

            this.Composer.Keyboard = this.Keyboard;

            _CurrentState = "Normal";
            VisualStateManager.GoToState(this, "Normal", false);

            //ThreadPool.QueueUserWorkItem(delegate
            //{
            //    Thread.Sleep(100);
            //    this.Dispatcher.BeginInvoke(delegate
            //    {
            //        VisualStateManager.GoToState(this, "Normal", true);
            //    });
            //});

        }

        private bool _HasThai = false;
        private void UpdateLength()
        {
            //int max = _HasThai ? 70 : 140;
            int max = 70;

            this.MessageCount.Text = "x" + ((this.Composer.Text.Length / max) + 1);
            this.CharRemaining.Text = (max - this.Composer.Text.Length % max).ToString();
        }

        private string _CurrentState;
        private void ChangeState(string state)
        {
            if (state == "Normal")
            {
                this.EnableAppBar(true);
                this.ApplicationBar.IsMenuEnabled = true;
            }
            else
            {
                this.EnableAppBar(false);
                this.ApplicationBar.IsMenuEnabled = false;
            }

            _CurrentState = state;
            VisualStateManager.GoToState(this, state, false);
        }

        private void EnableAppBar(bool enabled)
        {
            foreach (ApplicationBarIconButton item in this.ApplicationBar.Buttons)
            {
                item.IsEnabled = enabled;
            }
        }

        private void SaveState()
        {
            ApplicationSettings.Default["Composer"] = this.Composer.Text;
            ApplicationSettings.Default["ComposeTime"] = DateTime.Now.Ticks.ToString();
            ApplicationSettings.Default.Save();
        }

        private void LoadState()
        {
            this.Composer.Text = ApplicationSettings.Default["Composer"] as string;
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            this.SaveState();
            base.OnNavigatedFrom(e);
        }

        private bool _IsComposerFocused = false;
        private DateTime _LostFocusTime = DateTime.MinValue;

        private void SwitchLang_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (!_IsComposerFocused && DateTime.Now.Subtract( _LostFocusTime ).TotalMilliseconds > 500 )
                this.Composer.Focus();
        }

        private void Composer_GotFocus(object sender, System.Windows.RoutedEventArgs e)
        {
            _IsComposerFocused = true;

            VisualStateManager.GoToState(this, "EngIndicator", true);
            this.EnableAppBar(false);
        }

        private void Composer_LostFocus(object sender, System.Windows.RoutedEventArgs e)
        {
            _IsComposerFocused = false;
            _LostFocusTime = DateTime.Now;

            VisualStateManager.GoToState(this, "ThaiIndicator", true);
            this.EnableAppBar(true);
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (_CurrentState != "Normal")
            {
                this.ChangeState("Normal");

                e.Cancel = true;
                return;
            } 
        }

        private bool PreCheck()
        {
            if (string.IsNullOrEmpty(this.Composer.Text))
            {
                MessageBox.Show("type something first!", "hey!", MessageBoxButton.OK);
                return false;
            }

            if (ApplicationSettings.Default["Warning"] == null)
            {
                ApplicationSettings.Default["Warning"] = "1";
                MessageBox.Show("you might see Thai text in 'rectangles' but everything will be OK.", "note", MessageBoxButton.OK);
            }

            return true;
        }

        private void Help_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            this.ChangeState("Help");
        }

        #region Menus

        private void Restore_Click(object sender, EventArgs e)
        {
            this.LoadState();
        }

        private void Search_Click(object sender, EventArgs e)
        {
            this.PreCheck();

            SearchTask t = new SearchTask();
            t.SearchQuery = this.Composer.Text;
            t.Show();
        }

        private void Send_Click(object sender, System.EventArgs e)
        {
            this.ChangeState("SendSelection");
        }

        private void Share_Click(object sender, System.EventArgs e)
        {
            this.ChangeState("ShareSelection");
        }

        private void Settings_Click(object sender, System.EventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/Settings.xaml", UriKind.Relative));
        }

        #endregion

        #region AppBar

        private void Shift_Click(object sender, EventArgs e)
        {
            this.Keyboard.ToggleShift();
        }

        private void Alt_Click(object sender, EventArgs e)
        {
            this.Keyboard.ToggleAlt();
        }

        private void Space_Click(object sender, EventArgs e)
        {
            this.Composer.SendKey(' ');
        }

        private void Delete_Click(object sender, EventArgs e)
        {
            this.Composer.Delete();
        }

        #endregion

        private void Facebook_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (SociallySettings.FacebookOAuth == null)
            {
                if (MessageBox.Show("you did not setup facebook yet, do it now?", "hey!", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                    return;

                this.NavigationService.Navigate(new Uri("/Settings.xaml", UriKind.Relative));
                return;
            }

            if ( this.Composer.Text.Length > 420 )
            {
                MessageBox.Show( "your status is too long", "hey!", MessageBoxButton.OK );
                return;
            }

            string text = this.Composer.Text;
            FacebookApi.UpdateStatus(SociallySettings.FacebookOAuth, text,
            (ex, s) =>
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    if (ex != null)
                    {
                        MessageBox.Show("can't update status to facebook, " + ex.Message, "oops!", MessageBoxButton.OK);
                    }
                    {
                        MessageBox.Show("your status was updated!", "done", MessageBoxButton.OK);
                        this.ChangeState("Normal");
                    }
                });

            });
        }

        private void Twitter_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	Action setup = () =>
            {
                if (MessageBox.Show("you did not setup twitter yet, do it now?", "hey!", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                    return;

                this.NavigationService.Navigate(new Uri("/Settings.xaml", UriKind.Relative));
            };

            if (SociallySettings.TwitterOAuth == null)
            {
                setup();
                return;
            }
            else
            {
                if (string.IsNullOrEmpty(SociallySettings.TwitterOAuth.UserId))
                {
                    setup();
                    return;
                }
            }

            if ( this.Composer.Text.Length > 140 )
            {
                MessageBox.Show( "your tweet is too long", "hey!", MessageBoxButton.OK );
                return;
            }

            string text = this.Composer.Text;

            TwitterApi.Tweet(SociallySettings.TwitterOAuth, text,
            (ex, s) =>
            {
                this.Dispatcher.BeginInvoke(() =>
                    {
                        if (ex != null)
                        {
                            MessageBox.Show("can't tweet, " + ex.Message, "oops!", MessageBoxButton.OK);
                        }
                        {
                            MessageBox.Show("tweet sent!", "done", MessageBoxButton.OK);
                            this.ChangeState("Normal");
                        }
                    });

            });
        }

        private void SMS_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            this.PreCheck();

            PhoneNumberChooserTask numberChooser = new PhoneNumberChooserTask();
            numberChooser.Completed += delegate(object chooserSender, PhoneNumberResult chooserResult)
            {
                if (chooserResult.TaskResult == TaskResult.OK)
                {

                    SmsComposeTask t = new SmsComposeTask();
                    t.Body = this.Composer.Text;
                    t.To = chooserResult.PhoneNumber;
                    t.Show();
                }
            };

            numberChooser.Show();
        }

        private void Email_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            this.PreCheck();

            EmailAddressChooserTask emailChooser = new EmailAddressChooserTask();
            emailChooser.Completed += delegate(object chooserSender, EmailResult chooserResult)
            {
                if (chooserResult.TaskResult == TaskResult.OK)
                {
                    EmailComposeTask t = new EmailComposeTask();
                    t.Body = this.Composer.Text;
                    t.To = chooserResult.Email;
                    t.Show();
                }
            };

            emailChooser.Show();
        }

        private void Clear_Click(object sender, System.Windows.RoutedEventArgs e)
        {
        	if (MessageBox.Show( "you can still use restore menu to get it back :)", "clear?", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                this.SaveState();
                this.Composer.Text = string.Empty;
            }
        }


    }
}